const fs = require('fs')
const path = require('path')
const xlsx = require('node-xlsx')
const exec = require('child_process').exec
const moment = require('moment')
const database = require('./src/database/core')  // 引入数据库对象

/**
 * 修改配置就可以修改导出情况, 默认导出位置为"C:/UAV_database"
 */
const setting = {
    query: {
        // 搜索某个时间段的数据
        // 起始时间为:2020-02-02 07:00:00, 结束时间为2020-02-02 08:30:00
        saveTime: {
            $gt: "2020-02-02 07:00:00",
            $lt: "2020-02-02 08:30:00",
        }
    },
    isExportUavPosition : false,  // 是否导出无人机位置.如果导出,会新建导出数据文件夹,里面写入1.txt,2.txt等
    isOpen: true,  // 导出后是否自动打开文件
}

const nowTime = moment().format('MM-DD_HHmm')  // 当前时间
const mainDir = "C:/UAV_database"  // 主目录

database.record.find(setting.query, (err, docs) => {
    if (err) {
        console.log(`查询时出现错误, 错误信息为${err}`)
    }
    // 写入数据
    const writeData = []  // 待写入的数据
    const options = addTableHead(writeData)
    addTableContent(writeData, docs, setting.isExportUavPosition)

    // 生成buffer, 并写入文件
    const buffer = xlsx.build([{name: "Sheet1", data: writeData, options: options}])
    const outputFile = `导出数据_${moment().format('MM-DD_HHmm')}.xlsx`
    fs.writeFileSync(path.join(mainDir, outputFile), buffer)

    // 自动打开文件
    if(setting.isOpen){
        exec(`start ${path.join(mainDir, outputFile)}`)
    }

})

/**
 * 增加表头项, 返回列表自定义宽度
 * @param writeData
 * @returns {{'!cols': Array}}
 */
function addTableHead(writeData) {
    const options = {'!cols': []}  // 设置行宽
    const head = []
    const tableHead = ["序号", "实验时间", "搜索总用时", "搜索真目标用时", "真目标数量", "假目标数量", "无人机数量", "真目标分布",
        "假目标分布", "是否固定真目标", "无人机初始X轴位置", "无人机初始Y轴位置", "优化算法", "种群个数", "迭代次数"]
    for (let headName of tableHead) {
        head.push({
            v: headName,
            t: "s"
        })
        const width = headName.length * 15  // 列宽度与标题名字长度一致
        options['!cols'].push({wpx: width})
    }
    writeData.push(head)
    return options
}

/**
 * 增加内容项
 * @param writeData
 * @param docs
 */
function addTableContent(writeData, docs, isExportUavPosition) {
    let rowNum = 1
    isExportUavPosition  && fs.mkdirSync(path.join(mainDir, `导出数据_${nowTime}`))
    for (let doc of docs) {
        const row = []
        row.push(rowNum, doc.saveTime, doc.searchTotalTime, doc.searchTrueTargetTime, doc.config.trueTargetNum,
            doc.config.fakeTargetNum, doc.config.uavNum, doc.trueTargetPositions, doc.fakeTargetPositions,
            doc.config.isFixedTrueTarget, doc.config.initX, doc.config.initY, doc.config.method, doc.config.particleNum,
            doc.config.iterNum)
        if(isExportUavPosition){
            fs.writeFileSync(path.join(mainDir, `导出数据_${nowTime}`, `${rowNum}.txt`), doc.uavPosition)
        }
        writeData.push(row)
        rowNum += 1
    }
}

